
package net.biaji.android.alephclient;

import java.util.ArrayList;

import net.biaji.alephclient.Book;
import net.biaji.alephclient.LibAgent;
import net.biaji.android.alephclient.data.DataFusionManager;
import net.biaji.android.alephclient.data.DatabaseHelper;
import net.biaji.android.alephclient.views.BookAdapter;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.support.v4.app.ListFragment;
import android.view.View;
import android.widget.ListView;

public class SearchResultFragment extends ListFragment {

    private BookDetailShower shower;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        shower = (BookDetailShower) activity;
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        if (shower != null) {
            shower.onBookSelected(((Book) getListAdapter().getItem(position)).getSN());
        }
    }

    public void search(String key) {
        new AsyncTask<String, Void, ArrayList<Book>>() {
            String key = "";

            @Override
            protected void onPreExecute() {
                if (getView() != null)
                    setListShown(false);
            }

            @Override
            protected ArrayList<Book> doInBackground(String... bookName) {
                LibAgent agent = AgentSingleton.getInstance();
                key = bookName[0];
                return agent.searchByName(bookName[0]);

            }

            @Override
            protected void onPostExecute(ArrayList<Book> result) {
                if (result != null) {
                    setListAdapter(new BookAdapter(getActivity(), result));
                    saveSearch(key, result);
                    setListShown(true);
                } else {
                    setEmptyText(getString(R.string.search_result_empty));
                }

            }

        }.execute(key);
    }

    /**
     * 保存查询结果
     * 
     * @param key 查询关键词
     * @param result 查询结果
     */
    private void saveSearch(String key, final ArrayList<Book> result) {
        new Thread() {
            public void run() {
                DataFusionManager.getInstance(getActivity()).putBooks(result);
            }
        }.start();

    }
}
